import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { MessageBox } from 'element-ui'
import { generateSign } from '@/utils/signature'
import Cookies from 'js-cookie'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 在发送请求之前自定义请求头：token, 路由环境，应用code, 用户角色, 签名
    if (store.getters.token) {
      config.headers['token'] = getToken()
      const ROLEID = Number(Cookies.get('ROLEID'))
      const roleList = store.getters.rolesList
      if (ROLEID) {
        for (let a = 0; a < roleList.length; a++) {
          if (roleList[a].id === ROLEID) {
            config.headers['roleCode'] = roleList[a].code
          }
        }
      } else {
        config.headers['roleCode'] = roleList[0].code
      }
    }

    // 路由环境
    if (process.env.ENV_ROUTE) {
      config.headers['env'] = process.env.ENV_ROUTE
    }

    // 应用code
    config.headers['appCode'] = process.env.APP_CODE

    // 添加签名
    config.headers['sign'] = generateSign(process.env.KEY, process.env.APP_CODE)

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 1) {
      if (res.code === 118000014 || res.code === 118000015 || res.code === 118000016 || res.code === 1000 || res.code === 9000 || res.code === 9001) {
        MessageBox.confirm('Token已经过期，请重新登录', '信息', {
          showClose: false,
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else {
        MessageBox({
          message: res.msg || '请求异常',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject('error')
      }
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    MessageBox({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
